﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;


namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private string selectedFilePath;

        public Form1()
        {
            InitializeComponent();
        }

        // 选择C#源文件
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                using (OpenFileDialog openFileDialog = new OpenFileDialog())
                {
                    openFileDialog.Filter = "C# Source Files (*.cs)|*.cs"; // 仅显示C#源文件
                    if (openFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        selectedFilePath = openFileDialog.FileName;
                        label1.Text = $"{Path.GetFileName(selectedFilePath)}"; // 显示文件名
                        MessageBox.Show($"Selected file: {selectedFilePath}"); // 弹出选择的文件路径
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error selecting file: {ex.Message}"); // 异常处理
            }
        }

        // 统计文件内容
        private void button2_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(selectedFilePath))
            {
                MessageBox.Show("Please select a C# source file first.");
                return;
            }

            try
            {
                string fileContent = File.ReadAllText(selectedFilePath); // 读取文件内容

                // 统计原始行数和单词数
                int originalLineCount = fileContent.Split(new[] { Environment.NewLine }, StringSplitOptions.None).Length;
                int originalWordCount = CountWords(fileContent);

                // 删除空行和注释
                string[] lines = fileContent.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
                var cleanedLines = lines.Where(line => !string.IsNullOrWhiteSpace(line) && !line.TrimStart().StartsWith("//")).ToList();

                // 统计格式化后的行数和单词数
                int formattedLineCount = cleanedLines.Count;
                int formattedWordCount = CountWords(string.Join(Environment.NewLine, cleanedLines));

                // 统计每个单词出现的次数
                var wordCounts = CountWordOccurrences(cleanedLines);

                // 显示结果
                textBox1.Clear(); // 清空文本框
                textBox2.Clear();
                textBox3.Clear();
                textBox4.Clear();
                textBox1.AppendText($"{originalLineCount}\n"); // 显示原始行数
                textBox2.AppendText($"{originalWordCount}\n"); // 显示原始单词数
                textBox3.AppendText($"{formattedLineCount}\n"); // 显示格式化后的行数
                textBox4.AppendText($"{formattedWordCount}\n"); // 显示格式化后的单词数

                // 显示每个单词的出现次数
                listBox1.Items.Clear(); // 清空列表框
                foreach (var word in wordCounts)
                {
                    listBox1.Items.Add($"{word.Key}: {word.Value}"); // 显示单词和次数
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error processing file: {ex.Message}"); // 异常处理
            }
        }

        // 统计单词数的方法
        private int CountWords(string content)
        {
            // 使用正则表达式匹配单词（不包括标点符号）
            return Regex.Matches(content, @"\b\w+\b").Count;
        }

        // 统计每个单词出现次数的方法
        private Dictionary<string, int> CountWordOccurrences(IEnumerable<string> lines)
        {
            var wordCounts = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);

            foreach (var line in lines)
            {
                var words = Regex.Matches(line, @"\b\w+\b");
                foreach (Match word in words)
                {
                    string wordText = word.Value.ToLower();
                    if (wordCounts.ContainsKey(wordText))
                    {
                        wordCounts[wordText]++;
                    }
                    else
                    {
                        wordCounts[wordText] = 1;
                    }
                }
            }

            return wordCounts;
        }
    }
}
